package zhuanyeshixi2.basic.config;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import zhuanyeshixi2.basic.vo.BasicMsg;
import zhuanyeshixi2.basic.global.GlobalEnum;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 * 用于统一处理控制器层抛出的异常
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<BasicMsg> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        // 使用正确的错误码
        BasicMsg msg = BasicMsg.fail(GlobalEnum.ErrorCode.INVALID_PARAMETER, "参数验证失败");
        msg.setData(errors);

        return ResponseEntity.badRequest().body(msg);
    }

    /**
     * 处理业务逻辑异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<BasicMsg> handleIllegalArgumentException(IllegalArgumentException ex) {
        System.err.println("❌ 业务逻辑异常: " + ex.getMessage());
        ex.printStackTrace();

        BasicMsg msg = BasicMsg.fail(GlobalEnum.ErrorCode.INVALID_PARAMETER, ex.getMessage());
        return ResponseEntity.badRequest().body(msg);
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<BasicMsg> handleRuntimeException(RuntimeException ex) {
        System.err.println("❌ 运行时异常: " + ex.getMessage());
        ex.printStackTrace();

        BasicMsg msg = BasicMsg.fail(GlobalEnum.ErrorCode.UNKNOWN_ERROR, "系统错误: " + ex.getMessage());
        return ResponseEntity.status(500).body(msg);
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<BasicMsg> handleNullPointerException(NullPointerException ex) {
        System.err.println("❌ 空指针异常: " + ex.getMessage());
        ex.printStackTrace();

        BasicMsg msg = BasicMsg.fail(GlobalEnum.ErrorCode.UNKNOWN_ERROR, "系统错误: 空指针异常");
        return ResponseEntity.status(500).body(msg);
    }

    /**
     * 处理数据库异常
     */
    @ExceptionHandler(org.springframework.dao.DataAccessException.class)
    public ResponseEntity<BasicMsg> handleDataAccessException(org.springframework.dao.DataAccessException ex) {
        System.err.println("❌ 数据库异常: " + ex.getMessage());
        ex.printStackTrace();

        BasicMsg msg = BasicMsg.fail(GlobalEnum.ErrorCode.DATABASE_ERROR, "数据库操作失败: " + ex.getMessage());
        return ResponseEntity.status(500).body(msg);
    }

    /**
     * 处理所有其他异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<BasicMsg> handleException(Exception ex) {
        System.err.println("❌ 系统异常: " + ex.getMessage());
        ex.printStackTrace();

        BasicMsg msg = BasicMsg.fail(GlobalEnum.ErrorCode.UNKNOWN_ERROR, "系统错误: " + ex.getMessage());
        return ResponseEntity.status(500).body(msg);
    }
}